package com.madev.isellcrazyitems;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.madev.isellcrazyitems.entity.Product;
import com.madev.isellcrazyitems.entity.Sales;
import com.madev.isellcrazyitems.entity.User;
import com.madev.isellcrazyitems.handler.JSONController;
import com.madev.isellcrazyitems.handler.DatabaseHandler;
import com.madev.sales.R;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TableRow.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Cart extends Activity {
	//private Product product = new Product();
	private User customer = new User();
    private ArrayList<Integer> itemArr = new ArrayList<Integer>(), qtyArr = new ArrayList<Integer>(), posArr = new ArrayList<Integer>();
    private ArrayList<TextView> qtyTVArr = new ArrayList<TextView>(), totalTVArr = new ArrayList<TextView>();
    private ArrayList<ImageButton> leftArrowArr = new ArrayList<ImageButton>(), rightArrowArr = new ArrayList<ImageButton>();
    private ArrayList<Product> prodArr = new ArrayList<Product>();
    private TableLayout cartTable;
    private final DecimalFormat df = new DecimalFormat("#.00");
    private TextView totalPriceTV, totalQtyTV;
    private JSONController jController = new JSONController();
    private static String update_item_qty_url = "http://unifiq.5kportal.com/update_item_quantity.php";
    private static String create_sales_url = "http://unifiq.5kportal.com/create_sales.php";
    private static String create_sales_order_url = "http://unifiq.5kportal.com/create_sales_order.php";
    private static String sales_last_id_url = "http://unifiq.5kportal.com/retrieve_sales_last_id.php";
    private static final String TAG_SUCCESS = "success", TAG_ITEM = "item", TAG_ID = "id", TAG_SALES_ORDER_QUANTITY = "salesOrderQuantity", TAG_SALES_CUSTOMER_ID = "salesCustomerID", TAG_SALES_ORDER_PRODUCT_ID = "salesOrderProductID", TAG_SALES_PURCHASE_DATE = "salesPurchaseDate", TAG_SALES = "sales", TAG_SALES_ID = "salesID", TAG_SALES_ORDER_ID = "salesOrderID", TAG_QUANTITY = "quantity";
    private JSONArray salesJArr = null;
    private Menu myMenu;
    
	@SuppressWarnings("unchecked")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart_layout);
 
        totalPriceTV = new TextView(this);
        totalQtyTV = new TextView(this);
        totalPriceTV.setGravity(Gravity.CENTER);
        totalQtyTV.setGravity(Gravity.CENTER);
        cartTable = (TableLayout) findViewById(R.id.cart_table);
        
        Bundle bundle = getIntent().getExtras();
        itemArr = bundle.getIntegerArrayList("itemArr");
        qtyArr = bundle.getIntegerArrayList("qtyArr");
        DatabaseHandler productHandler = new DatabaseHandler(getApplicationContext());
        prodArr = productHandler.getProducts();
        productHandler.close();
        customer = (User) bundle.getSerializable("customer");
        LayoutParams ww = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        
        for (int x = 0; x < itemArr.size(); x++){
        	for (int y = 0; y < itemArr.size(); y++){
        		if (x != y){
        			if (itemArr.get(x) == itemArr.get(y)){
        				qtyArr.set(x, qtyArr.get(x) + qtyArr.get(y));				
        				itemArr.remove(y);
        				qtyArr.remove(y);
        				y--;
        			}
        		}
        	}
        }
        
        for (int a = 0; a < itemArr.size(); a++){
        	for (int b = 0; b < prodArr.size(); b++){
            	if (Integer.valueOf(prodArr.get(b).getProductID()).equals(itemArr.get(a))){
            		posArr.add(b);
            		break;
            	}
        	}
        }
        
        double totalPrice = 0;
        int totalQty = 0;
       
       
        for (int i = 0; i < itemArr.size(); i++){
        	final TableRow tr = new TableRow(this);
    		TextView nameTV = new TextView(this), priceTV = new TextView(this);
			final TextView qtyTV = new TextView(this), totalTV = new TextView(this);
    		ImageButton deleteIcon = new ImageButton(this);
			final ImageButton leftArrow = new ImageButton(this);
			final ImageButton rightArrow = new ImageButton(this);

    		deleteIcon.setLayoutParams(ww);
    		deleteIcon.setPadding(5, 5, 5, 5);
    		nameTV.setLayoutParams(ww);
    		nameTV.setPadding(5, 5, 5, 5);
    		nameTV.setGravity(Gravity.CENTER);
    		priceTV.setLayoutParams(ww);
    		priceTV.setPadding(5, 5, 5, 5);
    		priceTV.setGravity(Gravity.CENTER);
    		qtyTV.setLayoutParams(ww);
    		qtyTV.setPadding(10, 5, 10, 5);
    		qtyTV.setGravity(Gravity.CENTER);
    		totalTV.setLayoutParams(ww);
    		totalTV.setPadding(5, 5, 5, 5);
    		totalTV.setGravity(Gravity.CENTER);
    		leftArrow.setLayoutParams(ww);
    		leftArrow.setPadding(5, 5, 5, 5);
    		rightArrow.setLayoutParams(ww);
    		rightArrow.setPadding(5, 5, 5, 5);
    		
    		nameTV.setText(prodArr.get(posArr.get(i)).getProductName());
    		priceTV.setText("$" + prodArr.get(posArr.get(i)).getProductPrice());
    		qtyTV.setText(String.valueOf(qtyArr.get(i)));
    		
    		double qtyPrice = (Double.valueOf(prodArr.get(posArr.get(i)).getProductPrice()) * Double.valueOf(qtyArr.get(i)));   		
    		totalTV.setText("$" + df.format(qtyPrice));
    		
    		deleteIcon.setImageResource(R.drawable.delete_marker);
    		leftArrow.setImageResource(R.drawable.arrow_left);
    		rightArrow.setImageResource(R.drawable.arrow_right);
    		
    		final int z = i;
    		
    		deleteIcon.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					
					posArr.set(z, 0);
					itemArr.set(z, 0);
					qtyArr.set(z, 0);
					leftArrowArr.set(z, null);
					rightArrowArr.set(z, null);
					qtyTVArr.set(z, null);
					totalTVArr.set(z, null);
					cartTable.removeView(tr);
					
					if (cartTable.getChildCount() != 2){
						updateTotal(z, totalTV);
						
						/*for (int e = z; e <= itemArr.size() - 1; e++){
							setLeftArrowListener(leftArrowArr.get(e), z, qtyTVArr.get(e), totalTVArr.get(e));
				    		setRightArrowListener(rightArrowArr.get(e), z, qtyTVArr.get(e), totalTVArr.get(e));
						}*/
					}
					else{
						cartTable.removeAllViews();
			        	TableRow tr = new TableRow(Cart.this);
						TextView tv = new TextView(Cart.this);
						
			        	tv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			        	tv.setPadding(5, 5, 5, 5);
			        	tv.setGravity(Gravity.CENTER);
			        	tv.setText("No product in cart. \nProceed to purchase now! \u2191");
			        	
			        	tr.addView(tv);
			        	cartTable.addView(tr);
			        	cartTable.setStretchAllColumns(true);
			        	
			        	MenuItem mi = myMenu.findItem(R.id.menu_checkout);
			        	mi.setVisible(false);
			        	
					}
				}
    			
    		});
    		
    		setLeftArrowListener(leftArrow, z, qtyTV, totalTV);
    		setRightArrowListener(rightArrow, z, qtyTV, totalTV);
    		
    		totalPrice += qtyPrice;
    		totalQty += qtyArr.get(i);
    		
    		leftArrowArr.add(leftArrow);
    		rightArrowArr.add(rightArrow);
    		qtyTVArr.add(qtyTV);
    		totalTVArr.add(totalTV);
    		
    		tr.addView(deleteIcon);
    		tr.addView(nameTV);
    		tr.addView(priceTV);
    		tr.addView(leftArrow);
    		tr.addView(qtyTV);
    		tr.addView(rightArrow);
    		tr.addView(totalTV);
    		
    		cartTable.addView(tr);
    		}
        
        TableRow tr = new TableRow(this);
        
        totalQtyTV.setLayoutParams(ww);
        totalQtyTV.setLayoutParams(new TableRow.LayoutParams(4));
        totalQtyTV.setText(String.valueOf(totalQty));
        
        totalPriceTV.setLayoutParams(ww);
        totalPriceTV.setLayoutParams(new TableRow.LayoutParams(6));
        totalPriceTV.setText("$" + df.format(totalPrice));
                
        tr.addView(totalQtyTV);
        tr.addView(totalPriceTV);
        
        cartTable.addView(tr);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.cart, menu);
        myMenu = menu;
        return true;
    }
   
	@Override
	public boolean onOptionsItemSelected (MenuItem item){
		if (item.getItemId() == R.id.menu_purchase){
			removeEmptyRows();
			Bundle b = new Bundle();
			b.putIntegerArrayList("itemArr", itemArr);
			b.putIntegerArrayList("qtyArr", qtyArr);
			Intent purchaseScreen = new Intent(this, Purchase.class);
			purchaseScreen.putExtras(b);
	        startActivity(purchaseScreen);
	        finish();
		}
		else if (item.getItemId() == R.id.menu_checkout){
			String[] confirmedNameArr = new String[posArr.size()];
			double[] confirmedPriceArr = new double[posArr.size()];
			int[] confirmedQtyArr = new int[posArr.size()];

			String currentDate = dateToString(Calendar.getInstance().getTime());
			DatabaseHandler salesHandler = new DatabaseHandler(getApplicationContext());
			salesHandler.getWritableDatabase();
			salesHandler.createSales(customer.getUserId(), currentDate);
			
			Sales sales = salesHandler.retrieveSales(" ORDER BY " + TAG_SALES_ID + " DESC LIMIT 1");
			DatabaseHandler salesOrderHandler = new DatabaseHandler(getApplicationContext());
			salesOrderHandler.getWritableDatabase();
			
		    List<NameValuePair> salesParams = new ArrayList<NameValuePair>();
		    salesParams.add(new BasicNameValuePair(TAG_SALES_CUSTOMER_ID, String.valueOf(customer.getUserId())));
		    salesParams.add(new BasicNameValuePair(TAG_SALES_PURCHASE_DATE, currentDate));
		    jController.makeHttpRequest(create_sales_url, "POST", salesParams);
		    
		    List<NameValuePair> params = new ArrayList<NameValuePair>();
		    JSONObject salesObj = jController.makeHttpRequest(sales_last_id_url, "GET", params);
		    
		    int salesID = 0;
		    
		    try {
		        int success = salesObj.getInt(TAG_SUCCESS);

		        if (success == 1) {
		            salesJArr = salesObj.getJSONArray(TAG_SALES);

		            for (int a = 0; a < salesJArr.length(); a++) {
		                JSONObject jObject = salesJArr.getJSONObject(a);
		                salesID = jObject.getInt(TAG_SALES_ID);
		            }
		        } else {
		        }
		    } catch (JSONException e) {
		        e.printStackTrace();
		    }
		    
		   for (int i = 0; i < posArr.size(); i++){
			   int qty = Integer.valueOf(prodArr.get(posArr.get(i)).getProductStock()) - qtyArr.get(i);
			   List<NameValuePair> itemQtyParams = new ArrayList<NameValuePair>();
			   itemQtyParams.add(new BasicNameValuePair(TAG_ID, String.valueOf(prodArr.get(posArr.get(i)).getProductID())));
			   itemQtyParams.add(new BasicNameValuePair(TAG_QUANTITY, String.valueOf(qty)));
			   jController.makeHttpRequest(update_item_qty_url, "POST", itemQtyParams);
			   salesHandler.updateProductQuantity(Integer.valueOf(prodArr.get(posArr.get(i)).getProductID()), qty);
			   
			    List<NameValuePair> salesOrderParams = new ArrayList<NameValuePair>();
			    salesOrderParams.add(new BasicNameValuePair(TAG_SALES_ORDER_ID, String.valueOf(salesID)));
			    salesOrderParams.add(new BasicNameValuePair(TAG_SALES_ORDER_PRODUCT_ID, String.valueOf(prodArr.get(posArr.get(i)).getProductID())));
			    salesOrderParams.add(new BasicNameValuePair(TAG_SALES_ORDER_QUANTITY, String.valueOf(qtyArr.get(i))));

			    confirmedNameArr[i] = prodArr.get(posArr.get(i)).getProductName();
			    confirmedPriceArr[i] = Double.valueOf(prodArr.get(posArr.get(i)).getProductPrice());
			    confirmedQtyArr[i] = qtyArr.get(i);
			    
			    jController.makeHttpRequest(create_sales_order_url, "POST", salesOrderParams);
			    salesOrderHandler.createSalesOrder(sales.getSalesID().get(0), Integer.valueOf(prodArr.get(posArr.get(i)).getProductID()), qtyArr.get(i));
		   }
		   
		   salesHandler.close();
		   salesOrderHandler.close();
		   
			Bundle b = new Bundle();
			b.putSerializable("customer", customer);
		   
			Intent confirmationScreen = new Intent(this, Checkout.class);
			confirmationScreen.putExtra("nameArr", confirmedNameArr);
			confirmationScreen.putExtra("priceArr", confirmedPriceArr);
			confirmationScreen.putExtra("qtyArr", confirmedQtyArr);
			confirmationScreen.putExtras(b);
	        startActivity(confirmationScreen);
	        finish();
		}
		return true;
	}
	
	@SuppressLint("SimpleDateFormat")
	public String dateToString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    return sdf.format(date);
	}
	
	private void updateTotal(int z, TextView totalTV){
		double updatedTotalPrice = 0;
		int updatedTotalQty = 0;
		
		for (int b = 0; b < qtyArr.size(); b++){
			updatedTotalPrice += Double.valueOf(prodArr.get(posArr.get(b)).getProductPrice()) * Double.valueOf(qtyArr.get(b));
			updatedTotalQty += qtyArr.get(b);
		}
		
		double priceQty = (Double.valueOf(prodArr.get(posArr.get(z)).getProductPrice()) * Double.valueOf(qtyArr.get(z))); 
		totalTV.setText("$" + df.format(priceQty));
		totalPriceTV.setText("$" + df.format(updatedTotalPrice));
		totalQtyTV.setText(String.valueOf(updatedTotalQty));
	}
	
	private void setLeftArrowListener(ImageButton leftArrow, final int z, final TextView qtyTV, final TextView totalTV){	
		leftArrow.setOnClickListener(null);
		leftArrow.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				int current = Integer.valueOf(qtyTV.getText().toString());
				
				if (current > 1){
					current--;
					qtyTV.setText(String.valueOf(current));
					
					qtyArr.set(z, current);
					updateTotal(z, totalTV);
				}
			}
			
		});
	}
	
	private void setRightArrowListener(ImageButton rightArrow, final int z, final TextView qtyTV, final TextView totalTV){
		rightArrow.setOnClickListener(null);
		rightArrow.setOnClickListener(new OnClickListener(){
	
			@Override
			public void onClick(View v) {
				int current = Integer.valueOf(qtyTV.getText().toString());
				
				if (current < Integer.valueOf(prodArr.get(posArr.get(z)).getProductStock())){
					current++;
					qtyTV.setText(String.valueOf(current));
					
					qtyArr.set(z, current);
					updateTotal(z, totalTV);
			}
			
		}
			});
	}
	
	
	@Override
	public void onBackPressed() {
		removeEmptyRows();
		Bundle b = new Bundle();
		b.putIntegerArrayList("itemArr", itemArr);
		b.putIntegerArrayList("qtyArr", qtyArr);
		Intent purchaseScreen = new Intent(this, Purchase.class);
		purchaseScreen.putExtras(b);
    	setResult(RESULT_OK, purchaseScreen);
		super.onBackPressed();
	}
	
	public void removeEmptyRows(){
		for (int i = 0; i < itemArr.size(); i++){
			if (itemArr.get(i) == 0){
				itemArr.remove(i);
				qtyArr.remove(i);
				posArr.remove(i);
				i--;
			}
		}
	}
	
	
}
